import requests  
from zhipuai import ZhipuAI  
import json  

# 常量定义
DOMEN = "comm.chatglm.cn"  
KOMANDA_TOKEN = ""  # 这里需要填入实际的团队token
API_KLUCH = ""  # 这里需要填入实际的API key
ZAGOLOVKI = {  
    'Content-Type': 'application/json',  
    'Authorization': f'Bearer {KOMANDA_TOKEN}'  
}  
BAZOVYE_FUNCTSII = [
    "get_company_info", "get_company_register", "get_sub_company_info", 
    "get_legal_document", "search_company_name_by_info", 
    "search_company_name_by_register", "search_case_num_by_legal_document", 
    "search_company_name_by_sub_info"
]  

# ZhipuAI客户端初始化
klient = ZhipuAI(api_key=API_KLUCH)

# 工具列表定义
instrumenty = [  
    {  
        "type": "function",  
        "function": {  
            "name": "get_company_info",  
            "description": "根据公司名称获得该公司所有基本信息",  
            "parameters": {  
                "type": "object",  
                "properties": {  
                    "company_name": {  
                        "type": "string",  
                        "description": "公司名称",  
                    }  
                },  
                "required": ["company_name"],  
            },  
        }  
    },  
    {  
        "type": "function",  
        "function": {  
            "name": "search_company_name_by_info",  
            "description": "根据公司基本信息某个字段是某个值来查询具体的公司名称",  
            "parameters": {  
                "type": "object",  
                "properties": {  
                    "key": {  
                        "type": "string",  
                        "description": "公司信息表某字段",  
                    },  
                    "value": {  
                        "type": "string",  
                        "description": "公司信息表某字段对应的值",  
                    }  
                },  
                "required": ["key", "value"],  
            },  
        }  
    },  
    {  
        "type": "function",  
        "function": {  
            "name": "get_company_register",  
            "description": "根据公司名称获得该公司所有注册信息",  
            "parameters": {  
                "type": "object",  
                "properties": {  
                    "company_name": {  
                        "type": "string",  
                        "description": "公司名称",  
                    }  
                },  
                "required": ["company_name"],  
            },  
        }  
    },  
    {  
        "type": "function",  
        "function": {  
            "name": "search_company_name_by_register",  
            "description": "根据公司注册信息某个字段是某个值来查询具体的公司名称",  
            "parameters": {  
                "type": "object",  
                "properties": {  
                    "key": {  
                        "type": "string",  
                        "description": "公司注册信息表某字段",  
                    },  
                    "value": {  
                        "type": "string",  
                        "description": "公司注册信息表某字段对应的值",  
                    }  
                },  
                "required": ["key", "value"],  
            },  
        }  
    },  
    {  
        "type": "function",  
        "function": {  
            "name": "get_sub_company_info",  
            "description": "根据子公司名称获得该公司所有关联子公司信息",  
            "parameters": {  
                "type": "object",  
                "properties": {  
                    "company_name": {  
                        "type": "string",  
                        "description": "子公司名称",  
                    }  
                },  
                "required": ["company_name"],  
            },  
        }  
    },  
    {  
        "type": "function",  
        "function": {  
            "name": "search_company_name_by_sub_info",  
            "description": "根据关联子公司信息某个字段是某个值来查询具体的公司名称",  
            "parameters": {  
                "type": "object",  
                "properties": {  
                    "key": {  
                        "type": "string",  
                        "description": "关联子公司信息某字段",  
                    },  
                    "value": {  
                        "type": "string",  
                        "description": "关联子公司信息某字段对应的值",  
                    }  
                },  
                "required": ["key", "value"],  
            },  
        }  
    },  
    {  
        "type": "function",  
        "function": {  
            "name": "get_legal_document",  
            "description": "根据案号获得该案所有基本信息",  
            "parameters": {  
                "type": "object",  
                "properties": {  
                    "case_num": {  
                        "type": "string",  
                        "description": "案件号",  
                    }  
                },  
                "required": ["case_num"],  
            },  
        }  
    },  
    {  
        "type": "function",  
        "function": {  
            "name": "search_case_num_by_legal_document",  
            "description": "根据法律文书某个字段是某个值来查询具体的案号",  
            "parameters": {  
                "type": "object",  
                "properties": {  
                    "key": {  
                        "type": "string",  
                        "description": "法律文书某个字段",  
                    },  
                    "value": {  
                        "type": "string",  
                        "description": "法律文书某个字段对应的值",  
                    }  
                },  
                "required": ["key", "value"],  
            },  
        }  
    }  
]

# 解析函数调用的工具
def razobrat_vyzov_funktsii(response, soobsheniya):  
# 提取函数调用信息
funktsiya = response.choices[0].message.tool_calls[0].function  
argumenty_funktsii = funktsiya.arguments.replace('（', '(').replace('）', ')')
imya_funktsii = funktsiya.name

# 检查函数名是否在基础函数列表中
if imya_funktsii in BAZOVYE_FUNCTSII:
    url = f"https://{DOMEN}/law_api/{imya_funktsii}"  
    otvet = requests.post(url, json=json.loads(argumenty_funktsii), headers=ZAGOLOVKI)  
    
    # 记录消息
    soobsheniya.append(response.choices[0].message.model_dump())  
    soobsheniya.append({
        "role": "tool",  
        "content": f"{otvet.json()}",  
        "tool_call_id": response.choices[0].message.tool_calls[0].id  
    })  
    
    # 重新生成对话响应
    response = klient.chat.completions.create(
        model="glm-4",  # 填写需要调用的模型名称
        messages=soobsheniya,
        tools=instrumenty,
    )  
return response  

# 读取输入文件并处理每一行数据
with open('question(1).json', 'r', encoding='utf-8') as fail, open('base2_1.json', 'w', encoding='utf-8') as fail_vyvod:  
for stroka in fail:  
    dannye = json.loads(stroka)  
    print(dannye['question'])  
    soobsheniya = [{"role": "user", "content": f"{dannye['question']}"}]  
    
    otvet = klient.chat.completions.create(
        model="glm-4",  # 填写需要调用的模型名称
        messages=soobsheniya,
        tools=instrumenty,
        tool_choice="auto",  # 模型自主选择是否要调用函数
    )  
    
    while otvet.choices[0].finish_reason == "tool_calls":  
        print(otvet.choices[0].message)  
        otvet = razobrat_vyzov_funktsii(otvet, soobsheniya)  
        print(otvet.choices[0].message)  
    
    dannye['answer'] = otvet.choices[0].message.content  
    json.dump(dannye, fail_vyvod, ensure_ascii=False)  
    fail_vyvod.write('\n')